package com.youfang.sixthmedia;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.ViewFlipper;

import com.baidu.mapapi.LocationListener;
import com.gzit.common.async.AsynCallback;
import com.gzit.common.async.LoadingCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.LoadingDelegater;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.common.BaiduMapApplication;
import com.youfang.sixthmedia.common.BuddyAdapter;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.HeaderController;
import com.youfang.sixthmedia.message.GetNearByBuddyRequest;
import com.youfang.sixthmedia.message.GetNearByBuddyResponse;
import com.youfang.sixthmedia.message.model.Buddy;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnBottomListener;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnRefreshListener;

public class NearByBuddyActivity extends Activity {

	private int page = 1;
	private HeaderController controller;
	private GZITPullToRefreshListView listview;
	private BuddyAdapter adapter;

	private String lat;
	private String lon;
	private int accurancy;

	private LoadingDelegater loading = new LoadingDelegater();
	private LocationListener myLocationListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.nearby_buddy_activity);
		this.loading.init(this);

		this.listview = (GZITPullToRefreshListView) this
				.findViewById(R.id.listview);

		this.adapter = new BuddyAdapter(this);
		this.listview.setAdapter(adapter);
		this.controller = new HeaderController();
		this.controller.setup(listview, adapter);

		this.listview.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {

				remoteRefresh();

			}
		});
		this.listview.setOnBottomListener(new OnBottomListener() {

			@Override
			public void onBottomClick() {
				remoteMore();
			}

			@Override
			public void onBottom() {

			}
		});

		this.listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (YoufangContext.isLogined()) {
					Buddy buddy = (Buddy) parent.getItemAtPosition(position);
					gotoBuddyDetailActivity(buddy);
				} else {
					Net.gotoLoginActivity(NearByBuddyActivity.this);
				}

			}
		});

		// 定位当前的经纬度...
		myLocationListener = new LocationListener() {
			@Override
			public void onLocationChanged(Location location) {
				loading.hide();
				if (location == null) {
					AndroidUtils.toastShort("无法获取当前的位置信息!");
					return;
				}
				lon = String.valueOf(location.getLongitude());
				lat = String.valueOf(location.getLatitude());

				// remove location manager when we got the lon and lat...
				BaiduMapApplication app = (BaiduMapApplication) getApplication();
				app.getMapManager().getLocationManager()
						.removeUpdates(myLocationListener);

				remoteRefresh();

			}
		};

		// set the search range...
		this.findViewById(R.id.rangeBtn).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						showMenu();
					}
				});

		initMenu();

		startMyLocationSearch();

	}

	private void gotoBuddyDetailActivity(Buddy buddy) {

		Intent intent = new Intent();
		intent.setClass(this, BuddyDetailActivity.class);
		intent.putExtra("data", buddy);
		this.startActivity(intent);

	}

	ViewFlipper menuFlipper;
	PopupWindow popupSave;
	View menuLayout;

	private void initMenu() {
		menuFlipper = new ViewFlipper(this);
		menuFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_in));
		menuFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_out));
		menuFlipper.setFlipInterval(600000);
		menuLayout = this.getLayoutInflater().inflate(
				R.layout.nearby_range_menu, null);
		menuFlipper.addView(menuLayout);
		// tvSave = (TextView) menuLocalSaveLayout.findViewById(R.id.save);
		// tvCancel = (TextView) menuLocalSaveLayout.findViewById(R.id.cancel);
		popupSave = new PopupWindow(menuFlipper, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupSave.setFocusable(true);
		popupSave.setBackgroundDrawable(new BitmapDrawable());
		popupSave.update();

		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				hideMenu();
				switch (v.getId()) {
				case R.id.range0_btn: // 不限 0
					adapter.reset();
					accurancy = 0;
					listview.refresh();
					((Button) findViewById(R.id.rangeBtn)).setText("范围");
					break;
				case R.id.range1_btn:// 300 1
					adapter.reset();
					accurancy = 1;
					listview.refresh();
					((Button) findViewById(R.id.rangeBtn)).setText("300米");
					break;
				case R.id.range2_btn:// 500 2
					adapter.reset();
					accurancy = 2;
					listview.refresh();
					((Button) findViewById(R.id.rangeBtn)).setText("500米");
					break;

				case R.id.range3_btn: // 1000 3
					adapter.reset();
					accurancy = 3;
					listview.refresh();
					((Button) findViewById(R.id.rangeBtn)).setText("1公里");
					break;

				case R.id.range4_btn:// cancel
					break;

				}

			}
		};

		for (int id : new int[] { R.id.range0_btn, R.id.range1_btn,
				R.id.range2_btn, R.id.range3_btn, R.id.range4_btn }) {
			menuLayout.findViewById(id).setOnClickListener(listener);

		}

	}

	public static void setLayoutAlpha(Activity activity, float alpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = alpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
	}

	private void hideMenu() {
		popupSave.dismiss();
		setLayoutAlpha(this, 1f);
	}

	private void showMenu() {

		if (popupSave != null) {
			if (popupSave.isShowing()) {
				popupSave.dismiss();
			} else {
				setLayoutAlpha(this, 1f);
				popupSave.showAtLocation(this.findViewById(R.id.rangeBtn),
						Gravity.BOTTOM, 0, 0);
				menuFlipper.startFlipping();// 播放动画
			}
		}

	}

	@Override
	public void onBackPressed() {
		if (this.popupSave.isShowing()) {
			setLayoutAlpha(this, 1);
			this.hideMenu();
		}
		super.onBackPressed();
	}

	// 启动个人自己的定位
	private void startMyLocationSearch() {
		this.loading.show("正在定位中,请稍候...");
		BaiduMapApplication app = (BaiduMapApplication) this.getApplication();
		app.getMapManager().getLocationManager()
				.requestLocationUpdates(myLocationListener);
		app.enableAllProviders();
		app.startMapService();

	}

	public void remoteRefresh() {
		if (StringUtils.isBlank(lat)) {
			return;
		}

		// 重置页码
		page = 1;
		GetNearByBuddyRequest req = new GetNearByBuddyRequest();
		req.setLat(this.lat);
		req.setLon(this.lon);
		req.setAccurancy(accurancy);
		req.setPage(page);

		Net.doHttpRemote(this, req, new GetNearByBuddyResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onRefreshComplete();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GetNearByBuddyResponse resp = (GetNearByBuddyResponse) r;
						List<Buddy> dataList = resp.getDataList();
						adapter.reload(dataList);
						adapter.notifyDataSetChanged();
						listview.setSelection(1);

						// 控制楼房图标
						controller.onRefresh(dataList);

						// 页码递增
						page++;

						if (dataList.isEmpty()) {
							AndroidUtils.toastShort("当前条件下没有检索到数据");
						}

					}
				}, LoadingCallback.EMPTY);

	}

	public void remoteMore() {

		if (StringUtils.isBlank(lat)) {
			return;
		}
		GetNearByBuddyRequest req = new GetNearByBuddyRequest();
		req.setLat(this.lat);
		req.setLon(this.lon);
		req.setAccurancy(accurancy);
		req.setPage(page);

		Net.doHttpRemote(this, req, new GetNearByBuddyResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onBottomFinish();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GetNearByBuddyResponse resp = (GetNearByBuddyResponse) r;
						List<Buddy> dataList = resp.getDataList();

						adapter.addAll(dataList);
						adapter.notifyDataSetChanged();

						// logo控制器
						controller.onMore(dataList);

						// 页码递增
						page++;

					}
				}, LoadingCallback.EMPTY);

	}

	@Override
	protected void onStop() {
		super.onStop();
		BaiduMapApplication app = (BaiduMapApplication) getApplication();
		app.stopMapService();
		controller.onStop();
	}

}
